package io.renren.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.renren.common.utils.R;
import io.renren.entity.PricePoolEntity;
import io.renren.entity.Worker;
import io.renren.form.DrawWorker;
import io.renren.service.PricePoolService;
import io.renren.service.WorkerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 郑和明
 * @version 1.0 (createTime:2018-04-13 22:14:51)
 */
@RestController
@RequestMapping("/draw")
@Api(tags = "抽奖")
public class ApiWorkerController {


    private final WorkerService workerService;
    private final PricePoolService pricePoolService;

    @Autowired
    public ApiWorkerController(WorkerService workerService, PricePoolService pricePoolService) {
        this.workerService = workerService;
        this.pricePoolService = pricePoolService;
    }

    @RequestMapping(value = "workers", method = RequestMethod.GET)
    @ApiOperation("获取员工")
    public R getWorkers() {
        Wrapper<Worker> workerWrapper = new EntityWrapper<>();
        workerWrapper.where("rank=5");
        List<Worker> workers = workerService.selectList(workerWrapper);

        return R.ok().put("workers", workers);
    }


    @RequestMapping(value = "drawCount", method = RequestMethod.GET)
    @ApiOperation("第几次抽奖")
    public R drawCount() {
        PricePoolEntity entity = pricePoolService.selectByCurrent();

        if (entity != null) {
            return R.ok().put("current", entity);
        }

        return R.error("抽奖完毕");
    }

    @RequestMapping(value = "updateDraw", method = RequestMethod.POST)
    @ApiOperation("更新抽奖")
    public R updateDraw(@RequestBody DrawWorker drawWorker) {
        int rank = drawWorker.getRank();
        String[] numbers = drawWorker.getNumbers();
        PricePoolEntity entity = pricePoolService.selectByCurrent();
        if(entity==null){
            return R.error("抽奖完毕,请停止操作");
        }
        int per = pricePoolService.queryPerByRank(rank);

        if (numbers == null || numbers.length != per) {
            return R.error("抽奖失败，请重新抽奖");
        }

        int res = workerService.updateWorkers(rank, numbers);
        if (res == per) {
            pricePoolService.updateByRank(rank);
        }
        return R.ok();
    }


}
